package com.bocloud.cmp.service.utils;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.Result;

public class ExtendHttpClient extends HttpClient {

	private static Logger logger = LoggerFactory.getLogger(ExtendHttpClient.class);

	public Result post(Map<String, Object> headers, Map<String, Object> params, String url,
			AbstractHttpEntity entity) {
		if (StringUtils.isEmpty(url)) {
			logger.error("Url is empty!");
			return new Result(false, "Empty URL");
		}
		logger.debug("Url is{} and Param is {}", url, params);
		url = assembleURI(url, params);
		httpPost = new HttpPost(url);
		buildHeader(httpPost, headers);
		httpPost.setConfig(config);
		httpPost.setEntity(entity);
		try {
			response = httpclient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			String responseContent = IOUtils.toString(httpEntity.getContent(), "utf-8");
			int status = response.getStatusLine().getStatusCode();
			result = resultBuilder.build(status);
			if (result.isSuccess()) {
				result.setMessage(responseContent);
			} else {
				logger.warn(responseContent);
			}
		} catch (IOException e) {
			logger.error("HttpClient IOException:", e);
			result = new Result(false, e.getMessage());
		} finally {
			close();
		}
		return result;
	}
}
